package com.roy.sms.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.roy.sms.model.User;

@Repository
public class UserDao {
	
	@Resource
	private SessionFactory sessionFactory;
	
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	public User add(User user){
		getSession().save(user);
		return user;
	}
	
	public User load(int id){
		return (User) getSession().load(User.class, id);
	}
	
	public void update(User user){
		getSession().update(user);
	}
	
	public void delete(int id){
		getSession().delete(load(id));
	}
	
	public int findCount(){
		String hql = "select count(user) from User user";
		Long count =(Long) getSession().createQuery(hql).uniqueResult(); 
		return count.intValue();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> findPage(int rowBeginIndex, int rowCount){
		Query query = getSession().createQuery("from User");
		query.setFirstResult(rowBeginIndex).setMaxResults(rowCount);
		return query.list();
	}
	
	public User login(String username, String password){
		Query query = getSession().createQuery("from User u where u.username=? and u.password=?");
		query.setParameter(0, username).setParameter(1, password);
		return (User) query.uniqueResult();
	}
	
}
